<template>
  <div class="editTag">
    <el-input
      @blur="handleInputConfirm"
      @keyup.enter.native="handleInputConfirm"
      class="w100"
      ref="saveTagInput"
      size="small"
      v-if="inputVisible"
      v-model.trim="form"
    ></el-input>
    <el-tag
      :closable="closeable"
      :disable-transitions="true"
      :type="tagType"
      @click="showInput"
      @close="handleClose"
      class="pointer"
      v-else-if="value"
    >{{form}}</el-tag>
    <el-button @click="showInput" size="small" v-else>{{defaultVal}}</el-button>
  </div>
</template>

<script>
  export default {
    // name: 'editTag',
    props: {
      closeable: {
        type: Boolean,
        default: false
      },
      value: {
        type: [String, Number],
        default: ''
      },
      tagType: {
        type: String,
        default: ''
      },
      defaultVal: {
        type: String,
        default: '+ New Tag'
      }
    },
    watch: {
      value: {
        handler(val) {
          this.form = val
        },
        immediate: true
      }
    },
    data() {
      return {
        inputVisible: false,
        form: ''
      }
    },
    methods: {
      handleClose() {
        this.$emit('close')
      },

      showInput() {
        this.inputVisible = true
        this.$nextTick(() => {
          this.$refs.saveTagInput.$refs.input.focus()
        })
      },

      handleInputConfirm() {
        this.inputVisible = false
        if (this.form) {
          this.$emit('input', this.form)
          if (!this.value) {
            this.$emit('add', this.form)
            this.form = ''
          }
        } else {
          this.form = this.value
        }
      }
    }
  }
</script>
<style lang="scss" scoped>
  .editTag {
    display: inline-block;
    margin: 10px;
  }
</style>
